
// self_media_news_aggregator/frontend/js/app.js
document.addEventListener('DOMContentLoaded', function() {
    // 初始化变量
    const newsContainer = document.getElementById('news-container');
    const loadMoreBtn = document.getElementById('load-more');
    const searchInput = document.querySelector('input[type="text"]');
    let currentPage = 1;
    const itemsPerPage = 6;
    let filteredNews = [];
    
    // 加载新闻数据
    function loadNews(page = 1, searchTerm = '') {
        newsContainer.innerHTML = '';
        currentPage = page;
        
        // 获取并过滤新闻数据
        filteredNews = searchTerm ? 
            newsData.filter(news => 
                news.title.toLowerCase().includes(searchTerm.toLowerCase()) || 
                news.content.toLowerCase().includes(searchTerm.toLowerCase())
            ) : 
            [...newsData];
        
        // 计算分页
        const startIndex = (page - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const paginatedNews = filteredNews.slice(0, endIndex);
        
        // 渲染新闻卡片
        paginatedNews.forEach(news => {
            const newsCard = document.createElement('div');
            newsCard.className = 'news-card bg-white rounded-lg overflow-hidden';
            newsCard.innerHTML = `
                <img src="${news.image}" alt="${news.title}" class="w-full h-48 object-cover">
                <div class="p-4">
                    <div class="flex justify-between items-start mb-2">
                        <h3 class="text-lg font-semibold">${news.title}</h3>
                        <button class="favorite-btn p-1 rounded-full ${isFavorite(news.id) ? 'text-yellow-500' : 'text-gray-400'}" 
                                data-id="${news.id}">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                            </svg>
                        </button>
                    </div>
                    <p class="text-gray-600 text-sm mb-3">${news.content.substring(0, 100)}...</p>
                    <div class="flex justify-between items-center text-xs text-gray-500">
                        <span>${news.source}</span>
                        <span>${formatDate(news.date)}</span>
                    </div>
                </div>
            `;
            newsContainer.appendChild(newsCard);
        });
        
        // 显示/隐藏加载更多按钮
        loadMoreBtn.style.display = endIndex >= filteredNews.length ? 'none' : 'block';
        
        // 添加收藏按钮事件
        addFavoriteEvents();
    }
    
    // 检查是否已收藏
    function isFavorite(id) {
        const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
        return favorites.includes(id);
    }
    
    // 添加收藏事件
    function addFavoriteEvents() {
        document.querySelectorAll('.favorite-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
                
                if (favorites.includes(id)) {
                    favorites = favorites.filter(favId => favId !== id);
                    this.classList.remove('text-yellow-500');
                    this.classList.add('text-gray-400');
                } else {
                    favorites.push(id);
                    this.classList.remove('text-gray-400');
                    this.classList.add('text-yellow-500');
                }
                
                localStorage.setItem('favorites', JSON.stringify(favorites));
                
                // 添加点击动画
                this.classList.add('animate-ping');
                setTimeout(() => {
                    this.classList.remove('animate-ping');
                }, 300);
            });
        });
    }
    
    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
    
    // 搜索功能
    searchInput.addEventListener('input', function() {
        loadNews(1, this.value);
    });
    
    // 加载更多
    loadMoreBtn.addEventListener('click', function() {
        loadNews(currentPage + 1, searchInput.value);
    });
    
    // 分类导航点击事件
    document.querySelectorAll('.tag-cloud span').forEach(tag => {
        tag.addEventListener('click', function() {
            // 移除所有active类
            document.querySelectorAll('.tag-cloud span').forEach(t => 
                t.classList.remove('bg-blue-600', 'text-white')
            );
            
            // 添加当前active类
            this.classList.add('bg-blue-600', 'text-white');
            
            // 模拟分类筛选
            const category = this.textContent.trim();
            if (category === '全部') {
                loadNews(1, searchInput.value);
            } else {
                const filtered = newsData.filter(news => news.tags.includes(category));
                newsContainer.innerHTML = '';
                filtered.forEach(news => {
                    const newsCard = document.createElement('div');
                    newsCard.className = 'news-card bg-white rounded-lg overflow-hidden';
                    newsCard.innerHTML = `
                        <img src="${news.image}" alt="${news.title}" class="w-full h-48 object-cover">
                        <div class="p-4">
                            <h3 class="text-lg font-semibold mb-2">${news.title}</h3>
                            <p class="text-gray-600 text-sm mb-3">${news.content.substring(0, 100)}...</p>
                            <div class="flex justify-between items-center text-xs text-gray-500">
                                <span>${news.source}</span>
                                <span>${formatDate(news.date)}</span>
                            </div>
                        </div>
                    `;
                    newsContainer.appendChild(newsCard);
                });
                
                loadMoreBtn.style.display = 'none';
            }
        });
    });
    
    // 初始加载
    loadNews();
    
    // 提示正在开发中的功能
    const devFeatures = ['分享功能', '用户自定义新闻源', '新闻热度图表'];
    devFeatures.forEach(feature => {
        console.log(`${feature}正在开发中...`);
    });
});
